package public

import (
	"context"
	"errors"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"
	"server/vars"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegisterReq) (resp *types.TokenResp, err error) {
	user := &models.Users{}
	result := utils.Db.Where("username = ?", req.Username).Or("mobile = ?", req.Mobile).Or("email = ?", req.Email).First(user)
	if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("用户名或手机号或邮箱已存在")
	}
	copier.Copy(user, req)
	user.Salt = utils.RandStr(6)
	user.Password = utils.MD5(utils.MD5(req.Password) + user.Salt)
	err = utils.InsertData(user)
	if err != nil {
		return nil, err
	}

	jwtUser := utils.JwtUser{
		Id:       user.ID,
		Username: user.Username,
		Mobile:   user.Mobile,
		Email:    user.Email,
	}
	token, _ := utils.GetJwtToken(l.svcCtx.Config.Auth.AccessSecret, jwtUser)

	//把token存入redis
	utils.Rds.Setex("todo-token:"+token, utils.StructToJson(jwtUser), vars.CacheTime)
	utils.Rds.Setex("todo-user-id:"+utils.Int64ToString(int64(jwtUser.Id)), token, vars.CacheTime)

	resp = &types.TokenResp{
		UserId:   user.ID,
		Username: user.Username,
		Token:    token,
	}

	return resp, nil
}
